package bb.lanxing.util.img;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.BaseListAdapter;

public class ImageChooserActivity extends BaseActivity implements View.OnClickListener {
    private MenuItem confirmMenu;
    FrameLayout container;
    private String currentFolder;
    private FolderAdapter folderAdapter;
    TextView folderChooser;
    ListView folderList;
    private ImageChooserAdapter imageChooserAdapter;
    GridView imagesGrid;
    private int max;
    private final int requestDetail = 1;
    private boolean showingFolder;
    Toolbar toolbar;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_image_chooser);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        this.container = (FrameLayout) findViewById(R.id.image_chooser_container);
        this.imagesGrid = (GridView) findViewById(R.id.image_chooser_grid);
        this.folderList = (ListView) findViewById(R.id.image_chooser_folder_list);
        TextView textView = (TextView) findViewById(R.id.image_chooser_spinner);
        this.folderChooser = textView;
        textView.setOnClickListener(this);
        setSupportActionBar(this.toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
            supportActionBar.setDisplayShowTitleEnabled(true);
        }
        LocalImageHelper.init(getApplicationContext());
        Intent intent = getIntent();
        ArrayList<String> stringArrayListExtra = intent.getStringArrayListExtra(ImageChooserUtil.EXTRA_SELECTED_LIST);
        if (stringArrayListExtra == null) {
            ArrayList<Uri> parcelableArrayListExtra = intent.getParcelableArrayListExtra(ImageChooserUtil.EXTRA_SELECTED_LIST);
            if (parcelableArrayListExtra != null) {
                LocalImageHelper.getInstance().setCheckedUri(parcelableArrayListExtra);
            }
        } else {
            LocalImageHelper.getInstance().setCheckedPath(stringArrayListExtra);
        }
        this.max = intent.getIntExtra(ImageChooserUtil.EXTRA_MAX_SELECTABLE, -1);
        showLoadingPopWindow(getString(R.string.dialog_loading), false);
        LocalImageHelper.getInstance().LoadImageMap(new LocalImageHelper.OnLoadImageListener() {
            @Override
            public void onLoad(Map<String, List<LocalFile>> map) {
                ImageChooserActivity.this.setupImage(map);
            }

            @Override
            public void onUpdate(Map<String, List<LocalFile>> map) {
                if (map != null) {
                    ImageChooserActivity.this.folderAdapter.update(ImageChooserActivity.this.setupFolders(map), true);
                    ImageChooserActivity.this.imageChooserAdapter.update(map.get(ImageChooserActivity.this.currentFolder), true);
                }
            }
        });
    }


    public void setupImage(Map<String, List<LocalFile>> map) {
        closePopWindow();
        if (map == null) {
            return;
        }
        this.currentFolder = LocalImageHelper.KEY_ALL_IMAGES;
        FolderAdapter folderAdapter = new FolderAdapter(this, setupFolders(map));
        this.folderAdapter = folderAdapter;
        this.folderList.setAdapter((ListAdapter) folderAdapter);
        this.folderList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                ImageChooserActivity.this.currentFolder = adapterView.getAdapter().getItem(i).toString();
                ImageChooserActivity.this.imageChooserAdapter.update(LocalImageHelper.getInstance().getFolder(ImageChooserActivity.this.currentFolder), true);
                ImageChooserActivity.this.folderChooser.setText(ImageChooserActivity.this.currentFolder);
                ImageChooserActivity.this.toggleFolderList();
            }
        });
        this.folderChooser.setText(this.currentFolder);
        List<LocalFile> folder = LocalImageHelper.getInstance().getFolder(LocalImageHelper.KEY_ALL_IMAGES);
        if (folder == null || folder.isEmpty()) {
            return;
        }

        ArrayList<LocalFile> arrayList = new ArrayList<>(folder.size());
        arrayList.addAll(folder);
        ImageChooserAdapter imageChooserAdapter = new ImageChooserAdapter(this, arrayList);
        this.imageChooserAdapter = imageChooserAdapter;
        imageChooserAdapter.setOnSelectListener(new ImageChooserAdapter.OnSelectListener() {
            @Override
            public void onSelectFile(CompoundButton compoundButton, boolean z, LocalFile localFile) {
                ArrayList<LocalFile> checkedItems = LocalImageHelper.getInstance().getCheckedItems();
                if (z) {
                    if (ImageChooserActivity.this.max < 0 || checkedItems.size() < ImageChooserActivity.this.max) {
                        checkedItems.add(localFile);
                    } else {
                        ImageChooserActivity imageChooserActivity = ImageChooserActivity.this;
                        Toast.makeText(imageChooserActivity, imageChooserActivity.getString(R.string.toast_image_chooser_max, imageChooserActivity.max), Toast.LENGTH_SHORT).show();
                        compoundButton.setChecked(false);
                    }
                } else {
                    checkedItems.remove(localFile);
                }
                ImageChooserActivity.this.refreshFinishMenu(checkedItems);
            }
        });
        this.imagesGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                Log.i("img-choose", "onItemClick: " + i);
                Intent intent = new Intent(ImageChooserActivity.this, ImageChooseDetailActivity.class);
                intent.putExtra(ImageChooseDetailActivity.LOCAL_FILE_INDEX, i);
                intent.putExtra(ImageChooseDetailActivity.LOCAL_FILE_LIST, ImageChooserActivity.this.currentFolder);
                intent.putExtra(ImageChooseDetailActivity.LOCAL_FILE_MAX, ImageChooserActivity.this.max);
                ImageChooserActivity.this.startActivityForResult(intent, 1);
            }
        });
        this.imagesGrid.setAdapter((ListAdapter) this.imageChooserAdapter);
        refreshFinishMenu(LocalImageHelper.getInstance().getCheckedItems());
    }

    public ArrayList<String> setupFolders(Map<String, List<LocalFile>> map) {
        Set<String> keySet = map.keySet();
        ArrayList<String> arrayList = new ArrayList<>(map.size());
        arrayList.addAll(keySet);
        arrayList.remove(this.currentFolder);
        arrayList.add(0, this.currentFolder);
        return arrayList;
    }

    public void refreshFinishMenu(List<LocalFile> list) {
        StringBuilder sb;
        int size;
        if (this.max == 1) {
            if (list.size() != 1) {
                return;
            }
            sendResult();
        } else if (this.confirmMenu == null) {
        } else {
            if (list.isEmpty()) {
                this.confirmMenu.setTitle(R.string.finish);
            } else {
                if (this.max > 0) {
                    sb = new StringBuilder();
                    sb.append(list.size());
                    sb.append("/");
                    size = this.max;
                } else {
                    sb = new StringBuilder();
                    size = list.size();
                }
                sb.append(size);
                sb.append(" ");
                String sb2 = sb.toString();
                this.confirmMenu.setTitle(sb2 + getString(R.string.finish));
            }
            this.confirmMenu.setEnabled(!list.isEmpty());
        }
    }

    @Override
    public void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i == 1) {
            if (i2 == -1) {
                sendResult();
                return;
            }
            refreshFinishMenu(LocalImageHelper.getInstance().getCheckedItems());
            this.imageChooserAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_choose_image, menu);
        MenuItem findItem = menu.findItem(R.id.image_chooser_ok);
        this.confirmMenu = findItem;
        if (this.max > 1) {
            refreshFinishMenu(LocalImageHelper.getInstance().getCheckedItems());
        } else {
            findItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        int itemId = menuItem.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        if (itemId == R.id.image_chooser_ok) {
            sendResult();
        }
        return super.onOptionsItemSelected(menuItem);
    }

    private void sendResult() {
        Intent intent = new Intent();
        intent.putExtra(ImageChooserUtil.EXTRA_RETURN_PICTURES, LocalImageHelper.getInstance().getCheckedItems());
        setResult(-1, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        if (this.showingFolder) {
            toggleFolderList();
        } else {
            super.onBackPressed();
        }
    }

    public void toggleFolderList() {
        boolean z = this.showingFolder;
        TranslateAnimation translateAnimation = new TranslateAnimation(1, 0.0f, 1, 0.0f, 1, z ? 0.0f : 1.0f, 1, z ? 1.0f : 0.0f);
        translateAnimation.setDuration(300L);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationStart(Animation animation) {
                if (!ImageChooserActivity.this.showingFolder) {
                    ImageChooserActivity.this.folderList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (ImageChooserActivity.this.showingFolder) {
                    ImageChooserActivity.this.folderList.setVisibility(View.GONE);
                }
                ImageChooserActivity imageChooserActivity = ImageChooserActivity.this;
                imageChooserActivity.showingFolder = !imageChooserActivity.showingFolder;
            }
        });
        this.folderList.startAnimation(translateAnimation);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalImageHelper.getInstance().clearSelection();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.image_chooser_spinner) {
            toggleFolderList();
        }
    }


    public class FolderAdapter extends BaseListAdapter<String> {
        LayoutInflater inflater;

        public FolderAdapter(Context context, List<String> list) {
            super(context, list);
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = this.inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);//17367043//R.layout. 这个看看布局文件应该可以
            }
            TextView textView = (TextView) view;
            textView.setText(getItem(i));
            textView.setTextColor(ImageChooserActivity.this.getResources().getColor(R.color.abc_primary_text_material_light));
            return view;
        }
    }
}
